import axios from 'axios'
import qs from 'qs'
//创建axios实例
const $api=axios.create({
    header: {
        'Content-Type': 'application/json charset=utf-8'
        
    },
    baseURL:'/api',         //  api请求的路径
    timeout:1000,          //请求超时的时间
})
//请求头部添加Token
// axios.defaults.headers.common['Token'] = localStorage.getItem("token");
//请求拦截器
$api.interceptors.request.use(function(config){
     //在发送请求之前做些什么
    //  if(store.state.token){
    //     config.headers.common['Authentication-Token']=store.state.token
    //     }
     config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
     if (config.method === 'post') { // 2019/4/10  by zzq
        const data = qs.parse(config.data)
        config.data = qs.stringify({
         
          ...data
        })
          
      }
      if (config.method === 'get') { // 2019/4/10  by zzzq
        config.params = {
          ...config.params,
         
        }
      }
    return config
}, function (error) {
    return Promise.reject(error)
});
//响应拦截器
$api.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

//post请求
const post = function (url, params) {
    return new Promise((resolve, reject) => {
        $api({
          	url: url,
            method: 'post',
            data: params,
            headers: {
                'Content-Type': 'application/json',
            
            },
        }).then(res=> {
            resolve(res);
        }).catch(error => {reject(error);
        })
    });
}

//get请求
const get = function (url, params) {
    
    return new Promise((resolve, reject) => {
        $api({
          	url: url,
            method: 'get',
            params:params,
            headers: {
                'Content-Type':'application/json',
               
            },
        }).then(res=> {
            resolve(res);
        }).catch(error => {
            reject(error);
        })
    });
}

const deleteRequest = function (url, data) {
    return axios.request({
		url:'http://127.0.0.1:8088'+url,
        method: 'post',
        headers: {
            'Content-Type':'application/json, application/x-www-form-urlencoded, multipart/form-data'
        },
		data,
		// 重点在这里
		paramsSerializer: data => {
      		return qs.stringify(data, { indices: false })
    	}
	})
       

}


//暴露post、get方法
export default {post,get,$api,deleteRequest }